//
//	MiscStringSybase.m
//		Written by Don Yacktman Copyright (c) 1993 by Don Yacktman.
//				Version 1.95  All rights reserved.
//		This notice may not be removed from this source code.
//
//	This object is included in the MiscKit by permission from the author
//	and its use is governed by the MiscKit license, found in the file
//	"LICENSE.rtf" in the MiscKit distribution.  Please refer to that file
//	for a list of all applicable permissions and restrictions.
//	

#import <misckit/MiscString.h>

@implementation MiscString(Sybase)

// This category includes methods derived from the MOSybaseString class
// which are useful when dealing with Sybase databases.  I prefer this
// be a category, and not a subclass.

- convertUnixWildcardsToSybase
// Converts all occurences of "*" to "%" and all occurences of "?" to "_".
{
	[self replaceEveryOccurrenceOfChar:'*' withChar:'%' caseSensitive:YES];
	[self replaceEveryOccurrenceOfChar:'?' withChar:'_' caseSensitive:YES];
	return self;
}

- convertToCaseInsensitiveSearchString
// Modifies a MiscString by replacing all alphabetic
// characters with a case-insensitive sql expression.
// (ie "a" or "A" gets converted to "[aA]".
{
	NXStream *stream = NULL;
	long l;
	char *buf;
	const char *s;
	int i;
	
	if (!length) return self;
	
	// Convert to lower case
	[self toLower];
	s = [self stringValue];
	
	// Now create a stream to write the new version into
	stream = NXOpenMemory(NULL, 0, NX_READWRITE);
	
	// Write the new version
	for (i=0; i<length; i++)  {
		if (NXIsAlpha(s[i]))  {
			BOOL skip = NO;
			if ((i > 0) && (i < length - 2)) {
				if ((s[i-1] == '[') && (s[i+2] == ']')) {
					if (s[i] == s[i+1]) skip = YES;
				}
			}
			if (skip) {
				NXPutc(stream, s[i++]);
				NXPutc(stream, NXToUpper(s[i]));
			} else {
				NXPutc(stream, '[');
				NXPutc(stream, s[i]);
				NXPutc(stream, NXToUpper(s[i]));
				NXPutc(stream, ']');
			}
		}  else  {
			NXPutc(stream, s[i]);
		}
	}
	
	// Flush and get the position of the stream (ie the length)
	NXFlush(stream);
	l = NXTell(stream);
	// Go back to the beginning, malloc enough space, and read the stream
	// back out.
	NXSeek(stream, 0, NX_FROMSTART);
	NX_MALLOC(buf, char, l+1);
	NXRead(stream, buf, l);
	// Cap the buffer
	buf[l]='\0';
	// Free the stream
	NXCloseMemory(stream, NX_FREEBUFFER);
	
	// Set the stringValue of the new string to the case insensitive string
	// in the buffer.
	[self setStringValue:buf];
	NX_FREE(buf);
	return self;
}

- makeCaseInsensitiveSearchString
// Creates a new MiscString, replacing all alphabetic
// characters with a case-insensitive sql expression.
// (ie "a" or "A" gets converted to "[aA]".
{
	id ciss = [self copy];
	return [ciss convertToCaseInsensitiveSearchString];
}

@end
